﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;


public static class DataTableExtensions
{// function that set the given object from the given data row
    public static void SetItemFromRow<T>(T item, DataRow row)
        where T : new()
    {
        // go through each column
        foreach (DataColumn c in row.Table.Columns)
        {
            // find the property for the column
            PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

            // if exists, set the value
            if (p != null && row[c] != DBNull.Value)
            {
                p.SetValue(item, row[c], null);
            }
        }
    }

    // function that creates an object from the given data row
    public static T CreateItemFromRow<T>(DataRow row)
        where T : new()
    {
        // create a new object
        T item = new T();

        // set the item
        SetItemFromRow(item, row);

        // return 
        return item;
    }

    // function that creates a list of an object from the given data table
    public static List<T> CreateListFromTable<T>(DataTable tbl)
        where T : new()
    {
        // define return list
        List<T> lst = new List<T>();

        // go through each row
        foreach (DataRow r in tbl.Rows)
        {
            // add to the list
            lst.Add(CreateItemFromRow<T>(r));
        }

        // return the list
        return lst;
    }


    public static IList<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if (row.Table.Columns.Contains(property.Name))
            {
                if (row[property.Name] == System.DBNull.Value)
                    property.SetValue(item, null, null);
                else
                    property.SetValue(item, row[property.Name], null);
            }
        }
        return item;
    }
}
